<template>
  <el-container>
    <!--查询区和操作按钮区 -->
    <el-header>

      <el-row>
        <el-col :span="12">
          <el-form :inline="true" style="margin-top: 20px; margin-left: 80px;">
            <el-form-item label="角色名称">
              <el-input v-model="searchForm.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item style="margin-left: 30px">
              <el-button type="primary" icon="el-icon-search" @click="handleRoleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <div style="text-align: left;">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddRole">增加</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">删除</el-button>
        <el-button type="primary" icon="el-icon-video-play" @click="handleResouce">资源分配</el-button>
        <el-button type="primary" icon="el-icon-user-solid" @click="handleUser">用户分配</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
      </div>
      <el-table
        ref="roleList"
        v-loading="listLoading"
        :data="roleList"
        :empty-text="'暂无数据'"
        style="margin-top: 20px"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @row-dblclick="handleRowDoubleClick"
      >
        <el-table-column type="selection" align="center" width="60" />
        <el-table-column align="center" label="序号" width="80">
          <template slot-scope="scope">
            {{ scope.$index+1}}
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="name" align="center" width="120">
        </el-table-column>
        <el-table-column label="角色编号" prop="code" width="120" align="center">
        </el-table-column>
        <el-table-column label="角色备注" prop="remark" width="120" align="center">
        </el-table-column>
        <el-table-column label="所属公司" prop="companyName" width="120" align="center">
        </el-table-column>
        <el-table-column align="center" prop="orgName" label="所属机构" width="120">
        </el-table-column>
        <el-table-column align="center" prop="status" label="启用" width="110">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleCopy(scope.row)"
            >复制</el-button>
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              size="small"
              type="warning"
              @click="handlePermission(scope.row)"
            >查看权限</el-button>
          </template>
        </el-table-column>
        <!-- 隐藏列，绑定后端 ID -->
        <el-table-column v-if="false" prop="id" width="0"/>
      </el-table>
      <!-- 添加分页器 -->
      <el-pagination
        style="text-align: center; margin-top: 20px;"
        :current-page.sync="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!--增加、编辑、复制、查看权限对话框 -->
      <RoleDialog ref="AddRoleDialog" dialog-type="add" @fetch="fetchData"/>
      <RoleDialog ref="EditRoleDialog" dialog-type="update" @fetch="fetchData" />
      <RoleDialog ref="CopyRoleDialog" dialog-type="copy" @fetch="fetchData"/>
      <RoleDialog ref="PermissionDialog" dialog-type="view" />
      <!--用户分配对话框 -->
      <RoleDialog ref="AssignUsersDialog" dialog-type="user" />
      <!--资源分配对话框 -->
      <RoleDialog ref="AssignResourcesDialog" dialog-type="resource" />
    </el-main>
  </el-container>
</template>

<script>
import RoleDialog from '@/views/role/role-dialog.vue'
import {page, deleteRole} from "@/api/role";
import {mapActions} from "vuex";

export default {
  components: { RoleDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '启用': 'success',
        '禁用': 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      roleList: [],
      searchForm:{
        name: ''
      },
      listLoading: true,
      page: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 5,
      userRoleDTO:{
        roleList:[],
        userList:[]
      }
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    ...mapActions(['updateSelectedRoleIds']),

    fetchData() {
      console.log("fetch");
      this.listLoading  = true;
      const rolePageQueryDTO = {
        name: this.searchForm.name,
        page: this.page,
        pageSize: this.pageSize,
      };
      page(rolePageQueryDTO)
          .then(response => {
            this.roleList = response.data.records;
            this.total = response.data.total;
          })
          .catch(error => {
            console.error('获取数据出错', error);
          })
          .finally(() => {
            this.listLoading = false; // 数据加载完成
      });
    },
    handleRefresh() {
      this.fetchData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.fetchData();
    },
    /**
     * 角色模糊查询
     */
    handleRoleSearch() {
        this.fetchData();
    },
    handleAddRole() {
      // 处理新增用户逻辑
      this.$nextTick(() => {
        this.$refs.AddRoleDialog.onShow();
      })
    },
    handleDelete(row) {
      this.$confirm(`确定要删除角色 ${row.name} 吗?`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.id)
          .then(res => {
            // 检查响应以确认删除是否成功
            if (res.code === 1) {
              // 成功删除后的操作
              this.$message.success('成功删除角色');
              this.fetchData();
            } else {
              // 删除失败
              this.$message.error('删除角色失败');
            }
          })
          .catch(error => {
            // 处理请求出错的情况
            this.$message.error('删除角色失败，请重试');
          });
      }).catch(() => {
        //取消
      });
    },
    /**
     * 批量删除角色
     */
    handleBatchDelete() {
      // 获取选中的角色
      const selectedRoles = this.$refs.roleList.selection;

      if (selectedRoles.length === 0) {
        this.$message.error('请选择要删除的角色');
        return;
      }

      // 提取选中用户的 id 列表
      const ids = selectedRoles.map(row => row.id)
      // console.log(ids)

      // 弹出确认对话框
      this.$confirm('确定要删除选中的角色吗?', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击了确定按钮，执行删除操作
        deleteRole(ids)
          .then(res => {
            // 检查响应以确认删除是否成功
            if (res.code === 1) {
              // 成功删除后的操作
              this.$message.success('成功删除选中的角色')
              this.fetchData();
            } else {
              // 删除失败
              this.$message.error('删除角色失败');
            }
          })
          .catch(error => {
            // 处理请求出错的情况
            this.$message.error('删除角色失败，请重试');
          });
      }).catch(() => {
      })
    },
    handlePermission(row) {
      this.$nextTick(() => {
        this.$refs.PermissionDialog.onShow(row);
      });
    },
    /**
     * 双击行,显示编辑角色对话框
     */
    handleRowDoubleClick(row){
      this.$nextTick(() => {
        this.$refs.EditRoleDialog.onShow(row);
      })
    },
    handleEdit(row) {
      this.$nextTick(() => {
        this.$refs.EditRoleDialog.onShow(row);
      })
    },
    /**
     * 复制角色,回显角色数据
     */
    handleCopy(row) {
      this.$nextTick(() => {
        console.log(row.name);
        this.$refs.CopyRoleDialog.onShow(row);
      })
    },
    /**
     * 资源分配
     */
    handleResouce(row) {
      const selectedRoles = this.$refs.roleList.selection;
      // 提取选中用户的 name 列表
      const names = selectedRoles.map(row => row.name)
      // console.log(names)
      if (selectedRoles.length === 0) {
        this.$message.error('至少选择一个角色进行操作');
        return;
      }
      // 将格式化后的字符串赋给 row.selectedRoleNames
      row.selectedRoleNames = names.join('，');
      const roleIds = selectedRoles.map(role => role.id);
      this.$store.dispatch('updateSelectedRoleIds', roleIds);
      this.$nextTick(() => {
        this.$refs.AssignResourcesDialog.onShow(row);
      });
    },
    /**
     * 角色分配给用户
     */
    handleUser(row) {
      const selectedRoles = this.$refs.roleList.selection;
      if (selectedRoles.length === 0) {
        this.$message.error('至少选择一个角色进行操作');
        return;
      }

      const companyNames = new Set(selectedRoles.map(role => role.companyName));
      // console.log(companyNames);
      if (companyNames.size > 1) {
        this.$message.error('角色所属公司不同，无法同时分配');
        return;
      }

      const roleIds = selectedRoles.map(role => role.id);
      this.$store.dispatch('updateSelectedRoleIds', roleIds);
      // console.log(this.$store.state.selectedRoleIds);
      this.$refs.AssignUsersDialog.onShow(row);
    }
  }
}
</script>
